#install packages
library(panelView)
library(zoo)
library(StaggeredSynthDiD)
library(synthdid)
library(fect)
library(ggplot2)

#prepare data
laws = read.csv("statelaws.csv")
turnout = read.csv("stateturnout.csv")
laws = laws[laws$State!="",]
results <- list()

for (i in 1:nrow(laws)) {
  for (j in 2:ncol(laws)) { 
    if (!is.na(laws[i, j])) {
      if (laws[i, j] == "X") {
        results <- c(results, list(data.frame(STATE = laws$State[i], YEAR = colnames(laws)[j], Law = TRUE)))
      }else {
        results <- c(results, list(data.frame(STATE = laws$State[i], YEAR = colnames(laws)[j], Law = FALSE)))
      }
    }else {
      results <- c(results, list(data.frame(STATE = laws$State[i], YEAR = colnames(laws)[j], Law = FALSE)))
    }
  }
}
laws <- do.call(rbind, results)
laws$YEAR <-substring(laws$YEAR,2,10000)

data = merge(laws,turnout,by=c("STATE","YEAR"))
data = data[!(data$STATE %in%c("Texas")),]
data = data[data$YEAR != 1982&data$YEAR != 1980,]
data$Y = as.numeric(gsub(",","",data$VOTE_FOR_HIGHEST_OFFICE))/as.numeric(gsub(",","",data$VEP))*100

names(data)[names(data)=="Law"] <- "W"
names(data)[names(data)=="STATE"] <- "State"
names(data)[names(data)=="YEAR"] <- "Year"



data$W = as.numeric(data$W)

#create early vs late adopting groups
data$group = as.numeric(data$State %in% c("Arizona", "Georgia", "Indiana", "Ohio")) + 2*as.numeric(data$State %in% c("Alabama", "Kansas", "Mississippi", "North Dakota", "Tennessee", "Virginia", "Wisconsin"))


all_mc <- fect(Y ~ W, data = data[data$State != "Virginia" & data$State != "North Dakota",],
                 method = "mc",index = c("State","Year"), CV = TRUE, vartype = "jackknife",
                 se = TRUE, nboots = 2000,  force = "two-way",
                 parallel = TRUE, cores = 8, seed=1, min.T0 = 1, group = "group")
presidential_mc  <- fect(Y ~ W, data = data[as.numeric(data$Year)%%4 == 0& data$State != "Virginia" & data$State != "North Dakota",],
                          method = "mc",index = c("State","Year"), CV = TRUE, vartype = "jackknife",
                          se = TRUE, nboots = 2000,  force = "two-way", 
                          parallel = TRUE, cores = 8, seed=1,  group = "group")
midterm_mc  <- fect(Y ~ W, data = data[as.numeric(data$Year)%%4 == 2,],
                     method = "mc",index = c("State","Year"), CV = TRUE,
                     se = TRUE, nboots = 2000,  force = "two-way",vartype = "jackknife",
                     parallel = TRUE, cores = 8, seed=1, group = "group")

